package com.gulimall.auth_server.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.gulimall.api.feign.ThirdPartyClient;
import com.gulimall.auth_server.service.LoginService;
import com.gulimall.common.core.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.gulimall.common.constant.RedisConstants.AUTH_SERVER_SMS;
import static com.gulimall.common.enums.BizCodeEnum.SMS_CODE_EXC;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private ThirdPartyClient thirdPartyClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信验证码
     */
    @Override
    public Result<String> sendSms(String phone) {
        String code = RandomUtil.randomNumbers(5);
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(AUTH_SERVER_SMS + phone, code,60, TimeUnit.SECONDS);
        if(Boolean.TRUE.equals(success)){
            thirdPartyClient.sendSms(phone,code);
            log.info("验证码为：" + code);
            return Result.ok("发送验证码成功");
        }
        return Result.fail("验证码发送失败",SMS_CODE_EXC.getCode(),SMS_CODE_EXC.getDesc());
    }
}
